import { useEffect, useRef, useState, useCallback } from 'react';
import { Edit3 } from 'lucide-react';
import './Dialog.css';

/**
 * Dialog 表单对话框组件
 * @param {string} title - 标题
 * @param {string} message - 提示消息
 * @param {Array} fields - 字段数组，每个字段包含 { name, label, type, placeholder, defaultValue, required, validate }
 * @param {string} confirmText - 确认按钮文字
 * @param {string} cancelText - 取消按钮文字
 * @param {function} onConfirm - 确认回调，参数为所有字段值的对象
 * @param {function} onCancel - 取消回调
 */
export const Dialog = ({
  title = '输入',
  message,
  fields = [],
  confirmText = '确认',
  cancelText = '取消',
  onConfirm,
  onCancel
}) => {
  const modalRef = useRef(null);
  const [values, setValues] = useState({});
  const [errors, setErrors] = useState({});
  const firstInputRef = useRef(null);

  // 初始化字段值
  useEffect(() => {
    const initialValues = {};
    fields.forEach(field => {
      if (field.type === 'colorGroup') {
        // 对于 colorGroup 类型，初始化其子字段
        field.colors?.forEach(colorField => {
          initialValues[colorField.name] = colorField.defaultValue || '#000000';
        });
      } else {
        initialValues[field.name] = field.defaultValue || '';
      }
    });
    setValues(initialValues);
  }, [fields]);

  // 聚焦第一个输入框
  useEffect(() => {
    if (firstInputRef.current) {
      firstInputRef.current.focus();
    }
  }, []);

  const handleFieldChange = (name, value) => {
    setValues(prev => {
      const newValues = { ...prev, [name]: value };
      
      // 清除该字段的错误
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        
        // 重新验证可能依赖于该字段的其他字段
        fields.forEach(field => {
          if (field.validate && field.name !== name) {
            const fieldValue = newValues[field.name] || '';
            if (fieldValue.trim()) {
              const error = field.validate(fieldValue, newValues);
              if (error) {
                newErrors[field.name] = error;
              } else {
                delete newErrors[field.name];
              }
            }
          }
        });
        
        return newErrors;
      });
      
      return newValues;
    });
  };

  const validate = useCallback(() => {
    const newErrors = {};

    fields.forEach(field => {
      // colorGroup 类型的字段不需要验证（它的子字段会单独验证）
      if (field.type === 'colorGroup') {
        return;
      }

      const value = values[field.name];

      // 必填验证
      if (field.required) {
        // 对于字符串类型，检查是否为空或只有空格
        if (typeof value === 'string' && !value.trim()) {
          newErrors[field.name] = `${field.label}不能为空`;
          return;
        }
        // 对于其他类型（number, color等），检查是否为空值
        if (value === undefined || value === null || value === '') {
          newErrors[field.name] = `${field.label}不能为空`;
          return;
        }
      }

      // 自定义验证
      if (field.validate && value !== undefined && value !== null && value !== '') {
        const error = field.validate(value, values);
        if (error) {
          newErrors[field.name] = error;
        }
      }
    });

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [fields, values]);

  const handleConfirm = useCallback(() => {
    if (validate()) {
      onConfirm?.(values);
    }
  }, [validate, values, onConfirm]);

  // 处理键盘和点击事件
  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === 'Escape') {
        onCancel?.();
      } else if (e.key === 'Enter' && e.ctrlKey) {
        e.preventDefault();
        handleConfirm();
      }
    };

    const handleClickOutside = (e) => {
      if (modalRef.current && !modalRef.current.contains(e.target)) {
        onCancel?.();
      }
    };

    document.addEventListener('keydown', handleEscape);
    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [onCancel, handleConfirm]);

  return (
    <div className="dialog-overlay">
      <div ref={modalRef} className="dialog-modal">
        <div className="dialog-icon">
          <Edit3 size={32} strokeWidth={2} />
        </div>
        <div className="dialog-content">
          <h3 className="dialog-title">{title}</h3>
          {message && <p className="dialog-message">{message}</p>}
          
          <div className="dialog-fields">
            {fields.map((field, index) => (
              <div key={field.name} className="dialog-field">
                <label className="dialog-label">
                  {field.label}
                  {field.required && <span className="dialog-required">*</span>}
                </label>
                {field.type === 'select' ? (
                  <select
                    ref={index === 0 ? firstInputRef : null}
                    className={`dialog-select ${errors[field.name] ? 'dialog-input-error' : ''}`}
                    value={values[field.name] || ''}
                    onChange={(e) => handleFieldChange(field.name, e.target.value)}
                  >
                    {field.options?.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                ) : field.type === 'colorGroup' ? (
                  <div className="dialog-color-group">
                    {field.colors?.map((colorField) => (
                      <div key={colorField.name} className="dialog-color-item">
                        <input
                          type="color"
                          id={`color-input-${colorField.name}`}
                          className="dialog-color-input-hidden"
                          value={values[colorField.name] || colorField.defaultValue}
                          onChange={(e) => handleFieldChange(colorField.name, e.target.value)}
                        />
                        <label
                          htmlFor={`color-input-${colorField.name}`}
                          className="dialog-color-block"
                          style={{ backgroundColor: values[colorField.name] || colorField.defaultValue }}
                          title={colorField.label}
                        />
                        <span className="dialog-color-label">{colorField.label}</span>
                      </div>
                    ))}
                  </div>
                ) : field.type === 'color' && field.showAsBlock ? (
                  <div className="dialog-color-block-wrapper">
                    <input
                      type="color"
                      id={`color-input-${field.name}`}
                      className="dialog-color-input-hidden"
                      value={values[field.name] || field.defaultValue}
                      onChange={(e) => handleFieldChange(field.name, e.target.value)}
                    />
                    <label
                      htmlFor={`color-input-${field.name}`}
                      className="dialog-color-block"
                      style={{ backgroundColor: values[field.name] || field.defaultValue }}
                    />
                    <span className="dialog-color-value">{values[field.name] || field.defaultValue}</span>
                  </div>
                ) : (
                  <input
                    ref={index === 0 ? firstInputRef : null}
                    type={field.type || 'text'}
                    className={`dialog-input ${errors[field.name] ? 'dialog-input-error' : ''}`}
                    value={values[field.name] || ''}
                    onChange={(e) => handleFieldChange(field.name, e.target.value)}
                    placeholder={field.placeholder}
                  />
                )}
                {errors[field.name] && (
                  <span className="dialog-error">{errors[field.name]}</span>
                )}
              </div>
            ))}
          </div>
        </div>
        <div className="dialog-actions">
          <button 
            className="dialog-btn dialog-btn-cancel"
            onClick={onCancel}
          >
            {cancelText}
          </button>
          <button 
            className="dialog-btn dialog-btn-confirm"
            onClick={handleConfirm}
          >
            {confirmText}
          </button>
        </div>
      </div>
    </div>
  );
};

